package 二叉树;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Solution102 {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1);
        TreeNode treeNode1 = new TreeNode(2);
        TreeNode treeNode2 = new TreeNode(3);
        treeNode.left = treeNode1;
        treeNode.right = treeNode2;
        System.out.println(levelOrder(treeNode));


    }

    /**
     * BFS 打印层序遍历二叉树
     *
     * @param root
     * @return
     */
    public static List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        List<List<Integer>> result = new ArrayList<>();
        while (!queue.isEmpty()) {
            int length = queue.size();
            List<Integer> list = new ArrayList<>();
            while (length > 0) {
                TreeNode poll = queue.poll();
                if (poll != null) {
                    list.add(poll.val);
                    if (poll.left != null) {
                        queue.offer(poll.left);
                    }
                    if (poll.right != null) {
                        queue.offer(poll.right);
                    }
                }
                length--;
            }
            result.add(list);
        }
        return result;
    }


    /**
     * DFS 打印层序二叉树
     */
    public static List<List<Integer>> levelOrder2(TreeNode root) {
        List<Integer> chain = new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();
        dfs(root, 0, chain, res);
        return res;
    }

    public static void dfs(TreeNode root, int index, List<Integer> chain, List<List<Integer>> res) {
        if (root == null) {
            return;
        }
        chain.add(root.val);
        index++;


    }

}
